package com.myjpa.common.web;

import com.myjpa.common.json.JacksonMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Enumeration;

/**
 * @author: yaoll
 * @date: 2020-09-04
 * @verison: 1.0
 */
public class ServletUtils {

    private static final Logger logger = LoggerFactory.getLogger(ServletUtils.class);

    public static void writeJson(HttpServletResponse response, Object obj) {
        writeJson(response, JacksonMapper.toSimpleJson(obj));
    }

    public static void writeJson(HttpServletResponse response, String json) {
        response.setContentType("application/json;charset=UTF-8");
        PrintWriter out = null;
        try {
            out = response.getWriter();
            out.print(json);
            out.flush();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (out != null) {
                out.close();
            }
        }
    }

    public static Cookie getCookie(HttpServletRequest request, String name) {
        Cookie[] cookies = request.getCookies();
        if (cookies != null) {
            for (Cookie cookie : cookies) {
                if (name.equals(cookie.getName())) {
                    return cookie;
                }
            }
        }
        return null;
    }

    public static String getCookieValue(HttpServletRequest request, String name) {
        Cookie cookie = getCookie(request, name);
        return cookie == null ? null : cookie.getValue();
    }


    public static void showCookies(HttpServletRequest request) {
        Cookie[] cookies = request.getCookies();
        if (cookies != null) {
            for (Cookie cookie : cookies) {
                logger.info("cookie: {} {} {} {}", cookie.getName(), cookie.getValue(), cookie.getPath(), cookie.getDomain());
            }
        }
    }

    public static void showHeaders(HttpServletRequest request) {
        Enumeration<String> headerNames = request.getHeaderNames();
        if (headerNames != null) {
            while (headerNames.hasMoreElements()) {
                String name = headerNames.nextElement();
                logger.info("header: {} {}", name, request.getHeader(name));
            }
        }
    }

}
